<template>
  <div class="lead-list">
    <!-- 页面标题 -->
    <el-card
      class="header-card"
      shadow="never"
    >
      <div class="header-row">
        <h2>客户管理</h2>
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleAdd"
        >
          新建客户
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="客户总数"
            :value="leadStore.total"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="租房客户"
            :value="leadStore.rentLeads.length"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="买房客户"
            :value="leadStore.buyLeads.length"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="已标签客户"
            :value="leadStore.leadsWithTags.length"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-form
        :model="queryParams"
        inline
      >
        <el-form-item label="客户姓名">
          <el-autocomplete
            v-model="queryParams.name"
            :fetch-suggestions="querySearchByName"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
            @select="handleSelectLead"
            @clear="handleSearch"
          >
            <template #default="{ item }">
              <div class="autocomplete-item">
                <span class="name">{{ item.name }}</span>
                <span class="phone">{{ item.phone }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="电话号码">
          <el-autocomplete
            v-model="queryParams.phone"
            :fetch-suggestions="querySearchByPhone"
            placeholder="请输入电话"
            clearable
            style="width: 200px"
            @select="handleSelectLead"
            @clear="handleSearch"
          >
            <template #default="{ item }">
              <div class="autocomplete-item">
                <span class="phone">{{ item.phone }}</span>
                <span class="name">{{ item.name }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="需求类型">
          <el-select
            v-model="queryParams.demand_type"
            placeholder="请选择需求类型"
            clearable
            style="width: 180px"
          >
            <el-option
              label="整租"
              value="rent_whole"
            />
            <el-option
              label="合租"
              value="rent_share"
            />
            <el-option
              label="短租"
              value="rent_short"
            />
            <el-option
              label="买房"
              value="buy"
            />
            <el-option
              label="卖房"
              value="sell"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签筛选">
          <el-select
            v-model="queryParams.tag_name"
            placeholder="请选择标签"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="tag in popularTags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.name"
            >
              <span>{{ tag.name }}</span>
              <span style="float: right; color: #999; font-size: 12px">
                {{ '⭐'.repeat(tag.level) }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="Refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-table
        v-loading="leadStore.loading"
        :data="leadStore.leads"
        stripe
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />

        <el-table-column
          prop="name"
          label="姓名"
          width="120"
        />

        <el-table-column
          prop="phone"
          label="电话"
          width="140"
        />

        <el-table-column
          prop="demand_type"
          label="需求类型"
          width="120"
        >
          <template #default="{ row }">
            <el-tag :type="getDemandTypeTag(row.demand_type)">
              {{ getDemandTypeText(row.demand_type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="budget_range"
          label="预算范围"
          width="150"
        />

        <el-table-column
          prop="tag_names"
          label="标签"
          min-width="200"
        >
          <template #default="{ row }">
            <div
              v-if="row.tag_names"
              class="tag-list"
            >
              <el-tag
                v-for="tagName in row.tag_names.split(',')"
                :key="tagName"
                :type="getTagType(tagName)"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px"
              >
                {{ tagName }}
              </el-tag>
            </div>
            <span
              v-else
              style="color: #999"
            >无标签</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="notes"
          label="备注"
          min-width="200"
          show-overflow-tooltip
        />

        <el-table-column
          prop="created_at"
          label="创建时间"
          width="180"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="280"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleMatchProperties(row)"
            >
              <el-icon><MagicStick /></el-icon>
              智能匹配
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :total="leadStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <LeadDialog
      v-model="dialogVisible"
      :lead-data="currentLead"
      @success="handleDialogSuccess"
    />

    <!-- 智能匹配对话框 -->
    <PropertyMatchDialog
      v-model="matchDialogVisible"
      :lead-id="currentMatchLeadId"
    />

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="客户详情"
      size="600px"
      direction="rtl"
    >
      <div
        v-if="detailData"
        class="detail-content"
      >
        <el-descriptions
          :column="1"
          border
        >
          <el-descriptions-item label="客户ID">
            {{ detailData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ detailData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="电话">
            {{ detailData.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="需求类型">
            <el-tag :type="getDemandTypeTag(detailData.demand_type)">
              {{ getDemandTypeText(detailData.demand_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预算范围">
            {{ detailData.budget_range || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="标签">
            <div v-if="detailData.tag_names">
              <el-tag
                v-for="tagName in detailData.tag_names.split(',')"
                :key="tagName"
                :type="getTagType(tagName)"
                style="margin: 4px"
              >
                {{ tagName }}
              </el-tag>
            </div>
            <span v-else>无标签</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ detailData.notes || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(detailData.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(detailData.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
/**
 * 客户列表页面
 * 完整实现版本
 */
import { ref, reactive, onMounted, watch } from 'vue'
import { useLeadStore } from '@/stores/lead'
import { leadApi } from '@/api'
import { logger } from '@/utils/logger'
import notify from '@/utils/notify'
import { Plus, Search, Refresh, MagicStick } from '@element-plus/icons-vue'
import LeadDialog from './LeadDialog.vue'
import PropertyMatchDialog from '@/components/PropertyMatchDialog.vue'
import type { Lead } from '@/api/types'
import dayjs from 'dayjs'
import { getTagType, getPopularTags, type Tag } from '@/api/tag'
import { debounce } from 'lodash-es'

// ========== Store ==========
const leadStore = useLeadStore()

// ========== 响应式数据 ==========
const queryParams = reactive({
  page: 1,
  page_size: 20,
  name: '',
  phone: '',
  demand_type: '',
  tag_name: '',
})

const dialogVisible = ref(false)
const drawerVisible = ref(false)
const matchDialogVisible = ref(false)
const currentLead = ref<Lead | null>(null)
const detailData = ref<Lead | null>(null)
const currentMatchLeadId = ref<number | null>(null)
const popularTags = ref<Tag[]>([])

// ========== 方法 ==========

/**
 * 查询列表
 */
const handleSearch = () => {
  leadStore.fetchLeads(queryParams)
}

/**
 * 姓名自动补全
 */
const querySearchByName = async (queryString: string, cb: (suggestions: any[]) => void) => {
  if (!queryString || queryString.length < 1) {
    cb([])
    return
  }

  try {
    const response = await leadApi.getList({
      page: 1,
      page_size: 10,
      name: queryString
    })

    const suggestions = response.items.map(lead => ({
      value: lead.name,
      ...lead
    }))

    cb(suggestions)
  } catch (error) {
    logger.error('Name autocomplete failed', error)
    cb([])
  }
}

/**
 * 电话自动补全
 */
const querySearchByPhone = async (queryString: string, cb: (suggestions: any[]) => void) => {
  if (!queryString || queryString.length < 3) {
    cb([])
    return
  }

  try {
    const response = await leadApi.getList({
      page: 1,
      page_size: 10,
      phone: queryString
    })

    const suggestions = response.items.map(lead => ({
      value: lead.phone,
      ...lead
    }))

    cb(suggestions)
  } catch (error) {
    logger.error('Phone autocomplete failed', error)
    cb([])
  }
}

/**
 * 选择客户后的处理
 */
const handleSelectLead = (item: any) => {
  queryParams.name = item.name
  queryParams.phone = item.phone
  handleSearch()
}

/**
 * 防抖搜索（输入停止500ms后自动触发）
 */
const debouncedSearch = debounce(() => {
  handleSearch()
}, 500)

/**
 * 监听搜索参数变化，自动触发搜索
 */
watch(
  () => [queryParams.name, queryParams.phone, queryParams.demand_type, queryParams.tag_name],
  () => {
    debouncedSearch()
  }
)

/**
 * 重置筛选
 */
const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    page_size: 20,
    name: '',
    phone: '',
    demand_type: '',
    tag_name: '',
  })
  handleSearch()
}

/**
 * 加载热门标签
 */
const loadPopularTags = async () => {
  try {
    const response = await getPopularTags(20)
    popularTags.value = response.data
  } catch (error) {
    console.error('加载热门标签失败:', error)
  }
}

/**
 * 新建客户
 */
const handleAdd = () => {
  currentLead.value = null
  dialogVisible.value = true
}

/**
 * 查看详情
 */
const handleView = async (row: Lead) => {
  await leadStore.fetchLead(row.id)
  detailData.value = leadStore.currentLead
  drawerVisible.value = true
}

/**
 * 编辑客户
 */
const handleEdit = (row: Lead) => {
  currentLead.value = row
  dialogVisible.value = true
}

/**
 * 删除客户
 */
const handleDelete = (row: Lead) => {
  notify.confirm(`确定要删除客户【${row.name}】吗？`, '提示').then(async () => {
    const success = await leadStore.deleteLead(row.id)
    if (success) {
      handleSearch()
    }
  })
}

/**
 * 智能匹配房源
 */
const handleMatchProperties = (row: Lead) => {
  currentMatchLeadId.value = row.id
  matchDialogVisible.value = true
}

/**
 * 对话框成功回调
 */
const handleDialogSuccess = () => {
  dialogVisible.value = false
  handleSearch()
}

/**
 * 获取需求类型标签
 */
const getDemandTypeTag = (
  demandType: string | undefined
): 'primary' | 'success' | 'warning' | 'danger' | 'info' | undefined => {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
    rent_whole: 'primary',
    rent_share: 'success',
    rent_short: 'warning',
    buy: 'danger',
    sell: 'info',
  }
  return demandType ? typeMap[demandType] : undefined
}

/**
 * 获取需求类型文本
 */
const getDemandTypeText = (demandType: string | undefined) => {
  const textMap: Record<string, string> = {
    rent_whole: '整租',
    rent_share: '合租',
    rent_short: '短租',
    buy: '买房',
    sell: '卖房',
  }
  return demandType ? textMap[demandType] || demandType : '-'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (datetime: string) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// ========== 生命周期 ==========
onMounted(() => {
  loadPopularTags()
  handleSearch()
})
</script>

<style scoped>
.lead-list {
  padding: 0;
}

.header-card {
  margin-bottom: 0;
}

.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-row h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.stat-card {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ai-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.detail-content {
  padding: 16px 0;
}

/* 自动补全样式 */
.autocomplete-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
}

.autocomplete-item .name {
  font-weight: 500;
  color: #303133;
  min-width: 80px;
}

.autocomplete-item .phone {
  color: #606266;
  font-size: 13px;
  min-width: 110px;
}
</style>
